package com.zixuan.sina.service.impl;

import com.zixuan.sina.config.websocket.WebSocketConfig;
import com.zixuan.sina.entity.MessageLog;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.service.UserReflectionShipService;
import com.zixuan.sina.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@Slf4j
@ServerEndpoint(value = "/api/ws/{userId}/{friendId}",configurator = WebSocketConfig.class)
public class WebSocketImpl {

    private static ApplicationContext applicationContext;
    public static void setApplicationContext(ApplicationContext applicationContext) {
        WebSocketImpl.applicationContext = applicationContext;
    }
    private UserService userService;

    private UserReflectionShipService userReflectionShipService;
    private static int onlineCount=0;
    private static ConcurrentHashMap<String, WebSocketImpl> webSockets = new ConcurrentHashMap<>();
    private Session session;
    private String userId;
    private String sendUserId;

    //连接建立成功调用方法
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId") String userId,@PathParam(value="friendId")String sendUserId,EndpointConfig config){
        String sessionId = (String) config.getUserProperties().get("sessionId");
        this.userId=userId;
        this.sendUserId=sendUserId;
        this.session=session;
        webSockets.put(userId,this);
        addOnlineCount();
       log.info("有人加入了！ 当前在线人数为:{}",getOnlineCount());
//            sendMessage("有新的连接加入了！");
            log.info("新连接加入了");
    }
//连接关闭调用方法
    @OnClose
    public void onClose(){
        webSockets.remove(userId);
        subOnlineCount();
        log.info("一个连接关闭！当前在线人数为:{}",getOnlineCount());
    }

    //收到客户端信息调用的方法
    @OnMessage
    public void onMessage(String message,Session session)  {
        System.err.println("来自客户端的消息:" + message);
        WebSocketImpl webSocket = webSockets.get(userId);
        try {
            //指定用户发送
            if(sendUserId!=null){
                boolean b = sendToUser(message, sendUserId);
                log.info("发送{}",b);
            }else {
                //todo:群发信息
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //指定用户发送信息
    public boolean sendToUser(String message, String sendUserId) throws IOException {
        userService = applicationContext.getBean(UserService.class);
        userReflectionShipService = applicationContext.getBean(UserReflectionShipService.class);
        if (webSockets.get(sendUserId) != null) {
            if (!userId.equals(sendUserId)) {
//                webSockets.get(sendUserId).sendMessage("用户" + sendUserId + "发来消息：" + message);
                WebSocketImpl webSocket = webSockets.get(sendUserId);

                webSocket.sendMessage(message);//todo:发送json串给前端 如何解析数据渲染聊天界面
                //todo:消息入库

                User sendUser = userService.findUserById(this.sendUserId);
                User currentUser = userService.findUserById(this.userId);
                MessageLog messageLog = new MessageLog();
                messageLog.setUserId(userId);
                messageLog.setSendId(this.sendUserId);
                messageLog.setUsername(currentUser.getNickName());
                messageLog.setSendName(sendUser.getNickName());
                messageLog.setMessage(message);
                userReflectionShipService.addMessage(messageLog);
                log.info("消息入库:{}",message);
                return false;


            } else {
                webSockets.get(sendUserId).sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return true;
            }
        } else {
            //如果用户不在线则返回不在线信息给自己
            //todo:此处是由于当前用户不在线 需要将消息存入数据库中
            //由于当前用户不在线 websocket里面没有当前用户的信息 所有需要查询数据库
            log.error("{}",userService);
            User sendUser = userService.findUserById(this.sendUserId);
            User currentUser = userService.findUserById(this.userId);
            MessageLog messageLog = new MessageLog();
            messageLog.setUserId(userId);
            messageLog.setSendId(this.sendUserId);
            messageLog.setUsername(currentUser.getNickName());
            messageLog.setSendName(sendUser.getNickName());
            messageLog.setMessage(message);
            userReflectionShipService.addMessage(messageLog);
            log.info("消息:{}入库!",message);
            return false;
        }
    }

    //发生错误时调用
    @OnError
    public void onError(Session session,Throwable error){
        log.error("出现了错误");
        error.printStackTrace();
    }

    private synchronized void subOnlineCount() {
        onlineCount--;
    }

    //发送消息
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private synchronized int getOnlineCount() {
    return onlineCount;
    }

    private synchronized void addOnlineCount() {
        onlineCount++;
    }
}
